package com.leyou.cart.intercept;

import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.cart.config.JwtProperties;
import com.leyou.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 项目: leyou
 *
 * @author 岩冰
 * @version 2018/10/20 11:09
 */
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginIntercept extends HandlerInterceptorAdapter {
    @Autowired
    private JwtProperties prop;

    private static final ThreadLocal<UserInfo> tl = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //权限坚定
        try {
            String token = CookieUtils.getCookieValue(request, prop.getCookieName());
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
            tl.set(userInfo);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       //完成钱删除用户星系
        tl.remove();
    }

    public static UserInfo geUserInfo() {
        return tl.get();
    }
}
